*
*	Correct priority-scores cutoffs
*

use "${raw_data_applications_${year}}", clear
	gen year = ${year}
	keep if eljaras == 1
	merge n:1 karkod szaknev szint munkarend fin_form using "${data_contracts_${year}}"
	drop if _m == 2
	drop _m
	
	gen admission_rank = felv_sorsz1 
	label define state_funded 0 "Self-funded" 1 "State-funded"
	
	do "${helpers_dir}/tidyVariableForWelfareAnalysis.do"
	
	merge 1:1 id rank using "${data_applications_ps_${year}}"
	drop if _m == 2
	drop _m

	* Admitted, priority score is below priority-score cutoff
	do "${helpers_dir}/addAdmittedBelowPSCutoff.do"

	* Rejected, priority score is above priority-score cutoff
	do "${helpers_dir}/addHasJustifiedEnvy.do"
	
	keep applicant_id rank contract_id state_funded priority_score ///
		priority_score_cutoff admission_rank karkod szaknev szint munkarend ///
		fin_form year

	gen ps_relevant = .
	replace ps_relevant = priority_score if rank <= admission_rank | admission_rank == .
	replace ps_relevant = . if priority_score == 0

	collapse (min) priority_score_min=ps_relevant ///
		(mean) priority_score_cutoff=priority_score_cutoff, ///
		by(contract_id state_funded karkod szaknev szint munkarend ///
		fin_form year)

	keep if state_funded == 1 
	keep if szint == 1 | szint == 3
	
	gen ps_cutoff_funded_corrected = priority_score_cutoff
	replace ps_cutoff_funded_corrected = 160 if priority_score_min >= priority_score_cutoff & year < 2011 & priority_score_cutoff != .
	replace ps_cutoff_funded_corrected = 200 if priority_score_min >= priority_score_cutoff & year == 2011 & priority_score_cutoff != .
	replace ps_cutoff_funded_corrected = 240 if priority_score_min >= priority_score_cutoff & year > 2011 & year < 2014 & priority_score_cutoff != .
	replace ps_cutoff_funded_corrected = 260 if priority_score_min >= priority_score_cutoff & year == 2014 & priority_score_cutoff != .
	
	keep karkod szaknev szint munkarend fin_form year ps_cutoff_funded_corrected
	
	save "${correct_ps_cutoffs_${year}}", replace
	